<?php


namespace Logic;


use Config\mysql;

class KeyHandle
{

    public static function toHandleKey()
    {
        //TODO 定时排查redis中的key是否存在异常，同步mysql与redis的数据
        $redis = RedisClientLogic::getInstance();
        if ($redis->exists(RANDOM_WISHES) === 0) { //不存在key的情况
        }
        if ($redis->exists(ORDER_WISHES) === 0) { //key
            //设置order_wishes
        }
        //存在key,检查数据是否同步
        //同步完设置每个key的过期时间
    }


    /**
     * 处理发送祝福语后的redis-key
     * @param $uId
     * @param $wishId
     * @param $token
     * @return array
     */
    public static function dealKey($uId, $wishId, $token)
    {
        $redis = RedisClientLogic::getInstance();
        try {
            $res = $redis->hSet(USER_WISHES, $uId, $wishId); //用户id与祝福语id集合
            $redis->sAdd(RANDOM_WISHES, $wishId);//存储到随机祝福语id集合中
            $redis->zAdd(ORDER_WISHES, ['NX'], 0, $wishId);//存储到有序祝福语id集合中
            $redis->hSet($token, 'my_wish_id', $wishId);
            if ($res == 1) { //首次发送祝福语，设置key的过期时间
                $redis->expire(USER_WISHES, 2592000);
                $redis->expire(RANDOM_WISHES, 2592000);
                $redis->expire(ORDER_WISHES, 2592000);
            }
        } catch (\RedisException $e) {
            $sql = "DELETE FROM `tbWishLog` where id = :id";
            $dbLink = mysql::mysql();
            $st = $dbLink->prepare($sql);
            $st->execute([':id' => $wishId]);
            return ['res' => -1, '系统异常--' . $e->getMessage(), []];
        }
    }

    public static function findKeyExists($uid, $token)
    {
        $redis = RedisClientLogic::getInstance();
        //查询这个用户是否发送过祝福语
        $sql = "SELECT id from `tbWishLog` where uid = :uid";
        $dbLink = mysql::mysql();
        $st = $dbLink->prepare($sql);
        $st->execute([':uid' => $uid]);
        $row = $st->fetch(\PDO::FETCH_ASSOC);
        if ($row) {
            try {
                $res = $redis->hSet(USER_WISHES, $uid, $row['id']); //用户id与祝福语id集合
                $redis->sAdd(RANDOM_WISHES, $row['id']);//存储到随机祝福语id集合中
                $redis->zAdd(ORDER_WISHES, ['NX'], 0, $row['id']);//存储到有序祝福语id集合中
                $redis->hSet($token, 'my_wish_id', $row['id']);
                if ($res == 1) { //首次发送祝福语，设置key的过期时间
                    $redis->expire(USER_WISHES, 2592000);
                    $redis->expire(RANDOM_WISHES, 2592000);
                    $redis->expire(ORDER_WISHES, 2592000);
                }
            } catch (\RedisException $e) {
                return ['res' => -1, '系统异常--' . $e->getMessage(), []];
            }
        }
    }


}